package com.asiainfo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * 打为jar包后也能找到配置文件，并以流的方式读取。<br>
 * InputStream is
 * =ClassLoaderUtil.getResourceAsStream("config/others/config.properties"
 * ,MainTest.class);<br>
 * if (null != is) { <br>
 * reader = new InputStreamReader(is,"UTF-8"); <br>
 * } <br>
 * 
 * @author luhf
 * @date 2013-1-13 下午8:01:58
 */
public class ClassLoaderUtil{
	private static final Logger log=LoggerFactory.getLogger(ClassLoaderUtil.class);
	
	static{
		log.debug("启动ClassLoaderUtil工具类!");
	}

	/**
	 * 私用构造主法.因为此类是工具类.
	 */
	public ClassLoaderUtil(){
		super();
	}

	public static URL getResource(String resourceName,Class<?> callingClass){
		URL url=Thread.currentThread().getContextClassLoader().getResource(resourceName);
		if(url==null){
			url=ClassLoaderUtil.class.getClassLoader().getResource(resourceName);
		}
		if(url==null){
			ClassLoader cl=callingClass.getClassLoader();
			if(cl!=null){
				url=cl.getResource(resourceName);
			}
		}
		if((url==null)&&(resourceName!=null)&&((resourceName.length()==0)||(resourceName.charAt(0)!='/'))){
			return getResource('/'+resourceName,callingClass);
		}
		if(url!=null){
			log.info("配置文件路径为= "+url.getPath());
		}
		return url;
	}

	public static InputStream getResourceAsStream(String resourceName,Class<?> callingClass){
		URL url=getResource(resourceName,callingClass);
		try{
			return (url!=null)?url.openStream():null;
		}catch(IOException e){
			log.error("配置文件"+resourceName+"没有找到! ",e);
			return null;
		}
	}

}